import React, { useState, useEffect } from 'react';
import { Title } from 'base/ctl/title';
import { get_mt, aks_d1 } from './cmd';
import { g_line, g_wsn } from 'db/state';
import { ck_int, obj_int, IkInput, useForm, uPlc, BaseDlg, ErrView, NuiBt } from 'sui';
import { get_gun, clear_gun } from 'base/api';
import { put_log } from 'base/ctl/log';

const MtTitle = ({ cur, sub }) => {
    const getView = () => {
        const getSub = () => {
            if (!sub) {
                return null;
            }

            return <div><span className="mx-4">{">>"}</span>{sub}</div>;

        };

        const getCur = () => {
            const v = get_mt(cur);
            if (!v) {
                return null;
            }

            return <div><span className="mx-4">{">>"}</span>{get_mt(cur)}</div>;
        };

        return (
            <div className="inline-flex">
                仓库管理
                {getSub()}
                {getCur()}
            </div>
        );
    };

    return <Title value={getView()} width="" className="mr-4 px-4"/>;
};

const Sbtn = ({ label, cl, hcmd, w="w-32" }) => (
    <NuiBt color={cl} className={`h-24 ml-8 ${w}`} hcmd={hcmd}>
        <div className="text-2xl">{label}</div>
    </NuiBt>
);

const SideBtn = ({ label, cl, hcmd, disabled }) => (
    <NuiBt color={cl} className="mt-1 ml-4 w-px-next" hcmd={hcmd} disabled={disabled}>
        <div className="text-2xl">{label}</div>
    </NuiBt>
);

const DlgCode = ({ open, setOpen, cur, hcmd, supply }) => {
    const [code, setCode] = useState("");
    const [err, setErr] = useState("");

    useEffect(() => {
        if (!open) {
            return;
        }

        setErr("");
        setCode("");
    }, [open]);

    const code_zc = (v) => {
        const supply_sn = v[1];
        const sn = v[2];

        let misc = v[3];
        misc = misc.split("*");
        if (misc < 4) {
            setErr(`扫码验证错误: 规格 ${v[3]}`);
            return;
        }

        const level = misc[0];
        const ball = misc[1];
        const std = misc[2];
        const sub = misc[3];

        const box = parseInt(v[4], 10);
        if (isNaN(box)) {
            setErr(`扫码验证错误: 箱数 ${v[4]}`);
            return;
        }

        const num = parseInt(v[6], 10);
        if (isNaN(num)) {
            setErr(`扫码验证错误: 总数量 ${v[6]}`);
            return;
        }

        const snum = num / box;

        setOpen(false);

        hcmd({
            ball: ball,
            level: level,
            std: std,
            sub: sub,
            sn: sn,
            box: box,
            snum: snum,
            supply: supply_sn,
        });
    };

    const code_donga = (v) => {
        const ball = v[0];
        const level = v[1];
        const std = v[2];
        const sub = v[3];
        const sn = v[4];

        const num = parseInt(v[6], 10);
        if (isNaN(num)) {
            setErr(`扫码验证错误: 总数量 ${v[6]}`);
            return;
        }

        const snum = num / 4;
        let supply_sn = "";

        if (supply) {
            const f = supply.find(d => d.des.indexOf("东阿") >= 0);
            if (f) {
                supply_sn = f.id;
            }
        }

        setOpen(false);

        hcmd({
            ball: ball,
            level: level,
            std: std,
            sub: sub,
            sn: sn,
            box: 4,
            snum: snum,
            supply: supply_sn,
        });
    };

    const code_aks = (tmp) => {
        let sub = tmp[0];
        const a = aks_d1(sub[5]);
        let b = aks_d1(sub[6]);
        b = parseInt(b, 10);
        if (isNaN(b)) {
            setErr(`扫码验证错误: 分规值 ${sub[6]}`);
            return;
        }

        sub = `${a}.${b}`;
        sub = parseFloat(sub);

        if (isNaN(sub)) {
            sub = "";
        }

        let ball = tmp[0];
        ball = ball.slice(13);
        ball = ball.split("/");

        const b1 = parseInt(ball[0], 10);
        const b2 = parseInt(ball[1], 10);

        if (isNaN(b1) || isNaN(b2)) {
            setErr(`扫码验证错误: 球径 ${tmp[0]}`);
            return;
        }

        ball = b1 * 25.4 / b2;
        ball = Math.round(ball * 10000) / 10000;
        ball = Math.round(ball * 1000) / 1000;

        const std = parseInt(tmp[1], 10);
        if (isNaN(std)) {
            setErr(`扫码验证错误: 规值 ${tmp[1]}`);
            return;
        }

        const sn = tmp[2].slice(2, -1);

        let supply_sn = "";

        if (supply) {
            const f = supply.find(d => d.des.indexOf("AKS") >= 0);
            if (f) {
                supply_sn = f.id;
            }
        }

        setOpen(false);

        hcmd({
            ball: ball,
            std: std,
            sub: sub,
            sn: sn,
            box: 1,
            supply: supply_sn,
        });
    };

    const hcode = (v) => {
        // v = '010S0J62NJ7017/16 +2 400104994A 075';
        put_log("code", v, "扫码");

        let tmp = v.split("^");
        if (tmp.length >= 7) {
            return code_donga(tmp);
        }

        tmp = v.split("#");
        if (tmp.length >= 7 && tmp[0] === "T") {
            return code_zc(tmp);
        }

        tmp = v.split(" ");
        tmp = tmp.filter(d => d);
        if (tmp.length >= 4) {
            return code_aks(tmp);
        }

        setErr(`无法识别此编码: ${v}`);
    };

    useEffect(() => {
        if (!open) {
            return;
        }

        const id = setInterval(() => {
            uPlc(null, "get",
                {
                    line: g_line(),
                    sn: g_wsn(),
                },
                r => {
                    const ret = get_gun(r);
                    if (!ret) {
                        return;
                    }

                    setCode(ret);
                    clear_gun();

                    hcode(ret);
                },
                e => setCode(null));
        }, 700);

        return () => clearInterval(id);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open]);

    return (
        <BaseDlg open={open} title="扫码">
            <ErrView err="请用扫枪扫描物料二维码" tp="info"/>
            <div className="ml-4 text-2xl">{code}</div>
            <div className="inline-flex justify-end">
                <NuiBt hcmd={() => setOpen(false)} className="mr-4 mb-3">取消</NuiBt>
            </div>
            <ErrView err={err}/>
        </BaseDlg>
    );
};

const DlgNum = ({ open, setOpen, hcmd, cur }) => {
    const [value, setValue] = useState();
    const form = useForm(setValue);

    useEffect(() => {
        if (!open) {
            return;
        }

        setValue(cur);
    }, [open, cur]);

    const hok = () => {
        const ck = {
            snum: v => ck_int(v, "单箱数量"),
            box: v => ck_int(v, "箱数"),
        };

        if (!form.hcheck(ck, value)) {
            return;
        }

        form.hclear();
        setOpen(false);

        hcmd({
            snum: obj_int(value, "snum"),
            box: obj_int(value, "box"),
        });
    };

    return (
        <BaseDlg open={open} title="入库">
            <IkInput label="单箱数量" value={value} form={form} name="snum" className="mt-2 mb-3 ml-4"/>
            <IkInput label="箱数" value={value} form={form} name="box" className="mt-2 mb-3 ml-4"/>
            <div className="inline-flex justify-end">
                <NuiBt hcmd={() => setOpen(false)} className="mr-4 mb-3">取消</NuiBt>
                <NuiBt hcmd={hok} className="mr-4 mb-3" color="green">确定</NuiBt>
            </div>
        </BaseDlg>
    );
};

export {DlgNum, DlgCode, SideBtn, Sbtn, MtTitle};
